<template>
<!-- 新增客观题 -->
    <div class="objsubMain">
      <div class="objsubContent">
        <h3>批量新增客观题</h3>
        <div class="gundongtiaotable">
          <div style="width:300px" class="leftinputWidth">
            <div style="padding-bottom:15px;">
              <el-radio v-model="ontinuousnum" label="1">起止题号</el-radio>
              <el-radio v-model="ontinuousnum" label="2">固定题号</el-radio>
            </div>
            <div class="nrlist" v-if="ontinuousnum == 1">
              <div style="display: flex;align-items: center;">
                  <el-input class="fxwidth" v-model="addobjquestion.startNum" placeholder="" oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                  <b style="padding:0 8px;">-</b>
                  <el-input class="fxwidth" v-model="addobjquestion.endNum"  placeholder="" oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                </div>
            </div>
            <div class="nrlist" v-if="ontinuousnum == 2">
              <div style="display: flex;align-items: center;">
                  <!-- <div style="display:none;">{{errorRows[scope.$index]}}</div> -->
                  <el-input class="fxwidth2" v-model="addobjquestion.fixedNum"
                    placeholder="请以，隔开" oninput="value=value.replace(/[^\d,]/g, '')"></el-input>
                </div>
            </div>
            <div class="nrlist1" style="padding-bottom:15px;">
              <b>试题题型</b>
              <el-radio-group v-model="addobjquestion.questiontype">
                <el-radio v-for="item in questiontypelist" :label="item.id" :key="item.id">{{ item.questionName }}</el-radio>
              </el-radio-group>
            </div>
            <div class="nrlist1" style="padding-bottom:15px;">
              <b>选项方向</b>
              <el-radio-group v-model="addobjquestion.optiondirection">
                <el-radio  v-for="item in questionclassifylist" :label="item.value" :key="item.value">{{item.label}}</el-radio>
              </el-radio-group>
            </div>
            <div class="nrlist">
              <span>选项数量</span>
              <div style="display: flex;align-items: center;">
                <el-input class="fxwidth1" v-model="addobjquestion.optionsNum"  placeholder=""></el-input>
              </div>
            </div>
            <div class="nrlist">
              <span>满分分值</span>
              <div style="display: flex;align-items: center;">
                <el-input class="fxwidth1" v-model="addobjquestion.fullscore"  placeholder=""></el-input>
              </div>
            </div>
            <el-button class="addquestionbox" @click="addquestionbox">添加试题</el-button>
            <div class="addquestionstbutton">
              <el-button @click="sureobj">确定</el-button>
              <el-button @click="cancelobj">取消</el-button>
            </div>
          </div>
          <el-table ref="multipleTable1" border stripe :data="objquestionlist" tooltip-effect="dark"
            style="width: 100%" @selection-change="handleSelectionChange1"
            :header-cell-style="{ background: '#D8E4F0', color: '#2A303B', fontWeight: '500' }"
            :height="600">
            <el-table-column label="题号编号" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.questionNumber"
                  @input="scope.row.questionNumber = onlyNumber(scope.row.questionNumber)" placeholder=""
                  class="fxwidth3"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="题型" width="120" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.basicQuestionTypeId" placeholder="请选择" class="selectbox fxwidth4">
                  <el-option v-for="item in questiontypelist" :key="item.id" :label="item.questionName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column> 
            <el-table-column label="选项数" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.optionCount"
                  @input="scope.row.optionCount = onlyNumber(scope.row.optionCount)" placeholder=""
                  class="fxwidth3"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="方向" width="120" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.direction" placeholder="请选择" class="selectbox fxwidth4">
                  <el-option v-for="item in questionclassifylist" :key="item.value" :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </template>
            </el-table-column> 
            <el-table-column label="满分" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.fullScore" placeholder=""
                  class="fxwidth3"></el-input>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center" width="100">
              <template slot-scope="scope">
                <div style="display: flex;align-items: center;justify-content: center;">
                  <el-button type="text" size="small" @click="deleteobjquestion(scope.$index)"
                    style="display: flex;align-items: center;color:#EC555A">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
</template>

<script>
import {addobjectquestion} from '../../api/paperinfo/paperinfo.js'
export default{
  props:['questiontypelist','pagevale','objectivelistdata'],
    data(){
        return{
            addobjquestion: {
                startNum: '',
                endNum: '',
                fixednum:'',
                questiontype:'',
                optiondirection:'',
                fullscore: '',
            },
            objquestionlist:[],
            questionclassifylist:[{label:'横向',value:1},{label:'纵向',value:2}],
            ontinuousnum:'1',
        }
    },
    methods:{
       validateFixedNumInput() {
        // 只允许数字和逗号，并自动过滤非法字符
        // this.addobjquestion.fixedNum = this.addobjquestion.fixedNum.replace(/[^\d,]/g, '');
        
        // 可选：禁止连续逗号（如 `1,,2` → `1,2`）
        // this.addobjquestion.fixedNum = this.addobjquestion.fixedNum.replace(/,+/g, ',');
        
        // 可选：去除开头或结尾的逗号（如 `,1,2,` → `1,2`）
        this.addobjquestion.fixedNum = this.addobjquestion.fixedNum.replace(/^,|,$/g, '');
      },
      //添加试题
      addquestionbox(){
         // 校验题号
        if (this.ontinuousnum == 1) {
          if (!this.addobjquestion.startNum || !this.addobjquestion.endNum) {
            this.$message.error('请填写起止题号');
            return;
          }
          if (parseInt(this.addobjquestion.startNum) > parseInt(this.addobjquestion.endNum)) {
            this.$message.error('起始题号不能大于结束题号');
            return;
          }
        } else if (this.ontinuousnum == 2) {
          if (!this.addobjquestion.fixedNum) {
            this.$message.error('请填写固定题号');
            return;
          }
          // 检查固定题号格式
          if (!/^\d+(,\d+)*$/.test(this.addobjquestion.fixedNum)) {
            this.$message.error('固定题号格式不正确，请使用逗号分隔数字');
            return;
          }
        }
        
        // 校验试题题型
        if (!this.addobjquestion.questiontype) {
          this.$message.error('请选择试题题型');
          return;
        }
        
        // 校验选项方向
        if (!this.addobjquestion.optiondirection) {
          this.$message.error('请选择选项方向');
          return;
        }
        
        // 校验选项数量
        if (!this.addobjquestion.optionsNum) {
          this.$message.error('请填写选项数量');
          return;
        }
        
        // 校验满分分值
        if (!this.addobjquestion.fullscore) {
          this.$message.error('请填写满分分值');
          return;
        }
         let questionNumbers = [];
        if(this.addobjquestion.startNum && this.addobjquestion.endNum){
          // alert('1111')
          const startNum = parseInt(this.addobjquestion.startNum);
          const endNum = parseInt(this.addobjquestion.endNum);
          for (let i = startNum; i <= endNum; i++) {
            questionNumbers.push(i.toString());
          }
        }
        if(this.addobjquestion.fixedNum){
          // alert('2222')
          questionNumbers = this.addobjquestion.fixedNum.split(',').map(num => num.trim());
        }
        let chunkSize = 1
        for (let i = 0; i < questionNumbers.length; i += chunkSize) {
          const chunk = questionNumbers.slice(i, i + chunkSize);
          
          this.objquestionlist.push({
            examTemplateId:parseInt(this.$route.query.templateId),
            questionNumber: chunk[0],
            basicQuestionTypeId:this.addobjquestion.questiontype, // 题型数组
            direction: parseInt(this.addobjquestion.optiondirection), // 选项方向数组
            optionCount:parseInt(this.addobjquestion.optionsNum), // 选项数量
            fullScore: this.addobjquestion.fullscore, // 满分分值
            page:this.pagevale
          });
        }
         console.info(this.objquestionlist)
        this.addobjquestion= {
              startNum: '',
              endNum: '',
              fixednum:'',
              questiontype:'',
              optiondirection:'',
              fullscore: '',
          }
      },
        cancelobj () {
            this.addobjquestionIshow = false
        },
        // 删除客观题行
        deleteobjquestion (index) {
            if (this.objquestionlist.length > 1) {
                this.objquestionlist.splice(index, 1);
                this.$message({
                type: 'success',
                message: '删除行成功!'
                });
            } else {
                this.$message({
                type: 'warning',
                message: '至少保留一行数据!'
                });
            }
        },
        // 格式化输入值
        formatInputValue (value) {
            return value === 0 ? '' : value;
        },
        onlyLetters (value) {
            return value.replace(/[^a-zA-Z,]/g, '');
        },
        onlyNumber (value) {
            return value.replace(/[^0-9.]/g, '');
        },
        onlyzzNumber (value) {
            return value.replace(/[^0-9]/g, '');
        },
        handleSelectionChange1 (val) {
            this.multipleSelection1 = val;
        },
        //保存客观题
        sureobj(){
          console.info('this.objectivelistdata',this.objectivelistdata)
          // return false
          const dataMap = new Map(
            this.objectivelistdata.map(d => [`${d.questionNumber}-${d.smallQuestionNumber}`, d])
          );

          // 2. 遍历 newarry 找匹配
          const hitList = this.objquestionlist.filter(n =>
            dataMap.has(`${n.questionNumber}-${n.smallQuestionNumber}`)
          );

          // 3. 提示
          if (hitList.length) {
            const msg = hitList
              .map(n => {
                const d = dataMap.get(`${n.questionNumber}-${n.smallQuestionNumber}`);
                return `题号 ${d.questionNumber}${d.smallQuestionNumber?'-':''}${d.smallQuestionNumber?d.smallQuestionNumber:''} 已存在`;
              })
              .join('；');
            this.$message.warning(msg);
            return
          }
            if (this.objquestionlist.length > 0) {
              addobjectquestion(this.objquestionlist).then(res => {
                if(res.code=200){
                  this.$emit('closeobjective',1)
                }else{
                    this.$message({
                    type: 'warning',
                    message: '保存失败!'
                    });
                }
                 
              })
            } else {
                this.$message({
                type: 'warning',
                message: '请添加客观题!'
                });
            }
        },
        cancelobj(){
            this.$emit('closeobjective',0)
        }
    }
}
</script>

<style scoped>
.objsubMain {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.75);
  z-index: 100;
}
.objsubContent {
  box-sizing: border-box;
  width: 1040px;
  height: 700px;
  background: #FFFFFF;
  box-shadow: 0px 4px 16px 0px rgba(85, 114, 146, 0.1);
  border-radius: 10px;
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  padding: 24px;
}

.objsubContent h3 {
  font-size: 18px;
  font-weight: normal;
}
.objsubattention {
  display: flex;
  font-size: 14px;
  color: #619CF5;
  padding: 10px 0 24px;
}

.gundongtiaotable {
  width: 100%;
  height: 360px;
  display: flex;
}

.gundongtiaotable::-webkit-scrollbar {
  width: 6px;
  background-color: #eee;
  border-radius: 10px;
}

.gundongtiaotable::-webkit-scrollbar-track {
  background-color: #eee;
  border-radius: 10px;
}

.gundongtiaotable::-webkit-scrollbar-thumb {
  background: #619CF5;
  border-radius: 10px;
}
.nrlist{
  display: flex;
  align-items: center;
  margin-bottom:20px;
}
.nrlist span{
  display: inline-block;
  padding-right:15px;
  width:80px;
}
.nrlis >>> .el-input{
  width:195px;
}
.nrlist >>> .el-input__inner{
  width:195px;
}
.nrlist:first-child >>> .el-input{
  width:90px;
}
.nrlist:first-child >>> .el-input__inner{
  width:90px;
}
.nrlist:first-child b{
  font-style:normal;
  padding:0 6px;
  font-weight: normal;
}
.nrlist1 b{
  display: block;
  font-weight:normal;
  padding-bottom:15px;

}
.nrlist1  >>> .el-checkbox-group{
  margin-bottom:20px;
}
.addquestionbox{
  width:278px;
  background:#1A48DB;
  text-align: center;
  line-height:30px;
  color:#fff;
  font-size:16px;
  border:none;
}
.addquestionstbutton{
  margin-top:20px;
  display: flex;
  justify-content: space-between;
  padding-right:20px;
}
.addquestionstbutton >>> .el-button{
  width:130px;
  line-height:30px;
  font-size:16px;
  border:none;
}
.addquestionstbutton >>> .el-button:first-child{
  background:#1A48DB;
  text-align: center;
  line-height:30px;
  color:#fff;
}
.addquestionstbutton >>> .el-button:last-child{
  background:rgba(26, 72, 219, 0.1);
  text-align: center;
  line-height:30px;
  color:#1A48DB;
}
.custom-table {
  width: 100%;
  border: 1px solid rgba(216, 228, 240, 0.5);
  border-radius: 4px;
  border-right: none;
  border-bottom: none;
}

/* 自定义表格内部元素的样式 */
.custom-table>>>.el-table__header-wrapper th {
  background-color: #E8F0FA;
  height: 42px;
  padding: 0;
  text-align: center;
  font-weight: normal
}

.custom-table>>>.el-table__row td {
  height: 42px;
  padding: 0;
  text-align: center;
  border-bottom: none;
  border-right: solid 1px rgba(216, 228, 240, 0.34);
  font-size: 14px;
}

.el-table .warning-row {
  background: #ffffff;
}

.el-table .success-row {
  background: #D8E4F0;
}

.el-table .el-table__cell {
  padding: 8px 0;
}
.fxwidth {
  font-size: 14px;
  color: #2A303B;
}

.fxwidth>>>.el-input__inner {
  width: 130px;
  height: 30px;
  background: #F2F6FB;
  border-radius: 10px;
  border: 1px solid #D8E4F0;
  padding: 0;
  text-align: center;
}
.fxwidth1 {
  font-size: 14px;
  color: #2A303B;
}

.fxwidth1 >>> .el-input__inner {
  box-sizing: border-box;
  width: 200px;
  height: 30px;
  background: #F2F6FB;
  border-radius: 10px;
  border: 1px solid #D8E4F0;
  padding: 0;
  text-align: left;
  padding-left:10px;
}
.fxwidth2{
  font-size: 14px;
  color: #2A303B;
}

.fxwidth2 >>> .el-input__inner {
  box-sizing: border-box;
  width: 281px;
  height: 30px;
  background: #F2F6FB;
  border-radius: 10px;
  border: 1px solid #D8E4F0;
  padding: 0;
  text-align: left;
  padding-left:10px;
}
.fxwidth3{
  font-size: 14px;
  color: #2A303B;
}

.fxwidth3 >>> .el-input__inner {
  box-sizing: border-box;
  width: 35px;
  height: 30px;
  background: #F2F6FB;
  border-radius: 10px;
  border: 1px solid #D8E4F0;
  padding: 0;
  text-align: center;
}
.fxwidth4{
  font-size: 14px;
  color: #2A303B;
}

.fxwidth4 >>> .el-input__inner {
  box-sizing: border-box;
  width: 80px;
  height: 30px;
  background: #F2F6FB;
  border-radius: 10px;
  border: 1px solid #D8E4F0;
  padding: 0;
  text-align: left;
  padding-left:10px;
}
.fxwidth4 >>> .el-input__icon {
  line-height:30px;
}
</style>